<?php

class ZFDulcet_Grid_Deploy_Table extends Bvb_Grid_Deploy_Table {

    private $_gridName = '';
    private $_paramsRemove = array();
    private $_session = null;

    /**
     *
     * @var ZFDulcet_Grid_Deploy_Table_Search
     */
    private $_formSearch;

    protected function _buildExtraRows($position) {
        $r = parent::_buildExtraRows($position);
        if (($position == 'beforePagination') and ($r != '')) {
            $r = '<tfoot>' . $r . '</tfoot>';
        }

        return $r;
    }
    
    public function clearParam($param)
    {
        if ((isset($this->_ctrlParams[$param])) and (!is_array($this->_ctrlParams[$param]))) {
             unset($this->_ctrlParams[$param]);
        }
        return $this;
    }
    
    protected function _buildFiltersValues() 
    {
        foreach ($this->_ctrlParams as $key => $value) {
            if (is_array($value)) {
                $this->_ctrlParams[$key] = join(',', $value);
            }
        }
        return parent::_buildFiltersValues();
    }

    public function __construct(array $options = array()) {
        parent::__construct($options);

        if (isset($options['session'])) {
            $this->setParamsSession($options['session'], $options['id']);
        }
    }

    public function deploy() {
        $content = preg_replace("#^<div id='{$this->getGridId()}'>|<\/div>$#", '', parent::deploy());

        $content = strtr($content, array(
            '{GRID_ID}' => $this->getGridId(),
        ));

        $x = array(
            'gridName' => $this->_gridName,
            'content' => $content,
            'formSearch' => $this->_formSearch,
        );
        return $x;
    }

    public function addFormatterDir($dir, $prefix) {
        $this->_formatter->addPrefixPath(trim($prefix, '_'), rtrim($dir, '/') . '/');
        return $this;
    }

    public function addTemplateDir($dir, $prefix, $type) {
        if (!isset($this->_templates[$type])) {
            $this->_templates[$type] = new Zend_Loader_PluginLoader();
        }

        $this->_templates[$type]->addPrefixPath(trim($prefix, "_"), $dir, $type);
        return $this;
    }

    public function enableSearch($options = null, ZFDulcet_Form $form = null) {
        if (null !== $form) {
            $this->_formSearch = $form;
        } else {
            $this->_formSearch = new ZFDulcet_Grid_Deploy_Table_Search($options);
        }

        $request = Zend_Controller_Front::getInstance()->getRequest();
        if (null !== ($q = $request->getParam('q'))) {
            if (null !== ($request->getParam('searchbt'))) {
                $this->clearParam('searchbt');
            }

            $this->_formSearch->populate(array(
                'q' => $q,
            ));
        }
    }

    public function getNameGrid() {
        return $this->_gridName;
    }

    /**
     * Retorna um parametro da sessao caso ele exista ou falso caso nao exista
     * @param string $param
     * @return mixed
     */
    public function getParamSession($param) {
        $params = $this->_session->{$this->getGridId()};

        return (isset($params[$param])) ? $params[$param] : null;
    }

    /**
     * Retorna todos os parametros da sessao
     * @return mixed
     */
    public function getParamsSession() {
        return $this->_session->{$this->getGridId()};
    }

    public function getUrl($paramsToRemove = '', array $extraParams = array()) {
        $paramsToRemove = array_merge((array) $paramsToRemove, $this->_paramsRemove);
        return parent::getUrl($paramsToRemove, $extraParams);
    }

    public function setNameGrid($gridName) {
        $this->_gridName = $gridName;
    }

    public function setParamsRemove($params) {
        $params = (array) $params;
        $this->_paramsRemove = array_merge($this->_paramsRemove, $params);
    }

    /**
     * Alimenta a sessao com os parametros vindos na url
     * 
     * @param Zend_Session_Namespace $session
     * @param string $id
     */
    public function setParamsSession(Zend_Session_Namespace $session, $id) {
        $request = Zend_Controller_Front::getInstance()->getRequest();
        $userParams = $request->getUserParams();
        $allParams = $request->getParams();
        $params = array_diff_assoc($allParams, $userParams);
        $this->_session = $session;

//        Limpar a sessao
//        $this->_session->unsetAll();

        if (!empty($params)) {
            $this->_session->unsetAll();
            $this->_session->{$id} = array();

            foreach ($allParams as $param => $value) {
                $this->_session->{$id}[$param] = $value;
            }
        } else {
            foreach ($userParams as $param => $value) {
                $this->_session->{$id}[$param] = $value;
            }
        }
    }

    protected function _buildGridTable($grids) {
        return '<tbody>' . parent::_buildGridTable($grids) . '</tbody>';
    }

    protected function _pagination() {
        return strtr(parent::_pagination(), array('&nbsp;' => ''));
    }

}